package com.example.plcopne.ui;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;


import com.blankj.utilcode.util.ToastUtils;
import com.boya.m53m513.M53M513Serial;
import com.boya.m53m513.SerialPortFinder;
import com.example.plcopne.R;
import com.example.plcopne.utils.RxUtils;

import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;


/**
 * 读取身份证信息
 *
 * @Author: zdl
 * @UpdateRemark: 更新说明
 */
public class IDCarReadActivity extends BaseActivity {

    private M53M513Serial SDK;
    public int Loop = 0;// 0 无线循环  1 单次
    public String SerialName = "";//串口名

    public Bitmap bmp;
    public String Name = "";
    public String Sex = "";
    public String Folk = "";
    public String Birthday = "";
    public String Address = "";
    public String ID = "";
    public String Issue = "";
    public String Begin = "";
    public String End = "";
    public String Count = "";
    public int iKind;
    public String sFp = "";
    public String EnglishName = "";
    public String AreaCode = "";
    public String Version = "";
    public String Kind = "";
    public Thread work;
    public volatile boolean th_Exit = false;



    private ImageView img;

    private TextView m_Info;
//    private FaceEngine faceEngine;


    private void EventOpen() {
        //初始化串口
        int handle = SDK.StartSerial(SerialName, 115200);
        ToastUtils.showShort("开始打开串口" + handle);
        switch (handle) {
            case -1: {
                Toast.makeText(this, "串口打开错误", Toast.LENGTH_SHORT).show();
                break;
            }
            case -2: {
                Toast.makeText(this, "设备错误...", Toast.LENGTH_SHORT).show();
                break;
            }
            default: {
                ToastUtils.showShort("启动读卡程序" + handle);
                //启动读卡线程
//                m_Sam.setText("SAM号 "+SDK.GetSAM());
                th_Exit = true;
                getCarData();
//                work = new WorkThread();
//                work.start();
                break;
            }
        }


    }

    Disposable disposable;

    private void getCarData() {
        Observable.interval(0, 1, TimeUnit.SECONDS)
                .map(new Function<Long, Integer>() {
                    @Override
                    public Integer apply(Long aLong) throws Exception {
                        int i = ThreadReadCard(0);
                        return i;
                    }
                })
                .compose(RxUtils.schedulers())
                .as(RxUtils.bindLifecycle(this))
                .subscribe(new Observer<Integer>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        disposable = d;
                    }

                    @Override
                    public void onNext(Integer integer) {
                        if (integer == 1) {
//                            processImage();

                            img.setImageBitmap(bmp);
                            m_Info.setText(Name + "\r\n" + Sex + "\r\n" + Folk + "\r\n" + Birthday + "\r\n" + Address + "\r\n" + ID + "\r\n" +
                                    Issue + "\r\n" + Begin + "-" + End + "\r\n" + Kind + "\r\n" + sFp);
                        } else {
//                            disposable.dispose();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }


    //人脸与身份证信息比对
//    private void processImage() {
//        //裁剪合适的身份证图片
//        Bitmap alignedBitmap = ArcSoftImageUtil.getAlignedBitmap(bmp, true);
//
//        int width = alignedBitmap.getWidth();
//        int height = alignedBitmap.getHeight();
//        byte[] bgr24 = ArcSoftImageUtil.createImageData(alignedBitmap.getWidth(), alignedBitmap.getHeight(), ArcSoftImageFormat.BGR24);
//        int transformCode = ArcSoftImageUtil.bitmapToImageData(alignedBitmap, bgr24, ArcSoftImageFormat.BGR24);
//        if (transformCode != ArcSoftImageUtilError.CODE_SUCCESS) {
//            showToast("f图片转换失败, code is " + transformCode);
//            return;
//        }
//
//        if (bgr24 != null) {
//
//            List<FaceInfo> faceInfoList = new ArrayList<>();
//            //人脸检测
//            int detectCode = faceEngine.detectFaces(bgr24, width, height, FaceEngine.CP_PAF_BGR24, faceInfoList);
//            if (detectCode != 0 || faceInfoList.size() == 0) {
//                showToast("人脸检测完成, code is " + detectCode + ", 人脸个数是 " + faceInfoList.size());
//                return;
//            }
//            UserCell userCell = LitePal.where("name=?", "胡波").findLast(UserCell.class);
//            FaceFeature mainFeature = new FaceFeature();
//            mainFeature.setFeatureData(userCell.feature);
//
//            FaceFeature faceFeature = new FaceFeature();
//            int res = faceEngine.extractFaceFeature(bgr24, width, height, FaceEngine.CP_PAF_BGR24, faceInfoList.get(0), faceFeature);
//            if (res == 0) {
//                FaceSimilar faceSimilar = new FaceSimilar();
//                int compareResult = faceEngine.compareFaceFeature(mainFeature, faceFeature, faceSimilar);
//                if (compareResult == ErrorInfo.MOK) {
//                    Log.e("tag", "相似度: " + faceSimilar.getScore());
//                } else {
//                    showToast(getString(R.string.compare_failed, compareResult));
//                }
//            }
//        }
//    }

    public int ThreadReadCard(int Fp) {
        //传index为0不带指纹读卡，其他数带指纹读卡.
        //传Loop参数0是连续读卡，1是单次读卡
        int ret = SDK.CardReader(Fp, Loop);//首先读卡
//            ToastUtils.showShort("读卡"+ret);
        if (ret == 1) {
            Loop = 1;
            bmp = SDK.CardPhoto(); //得到Bitmap对象，身份证头像.
            Name = SDK.CardName().trim();
            Sex = SDK.CardSex();
            Birthday = SDK.CardBirthday();
            Address = SDK.CardAddress().trim();
            ID = SDK.CardID();
            Issue = SDK.CardIssue();
            Begin = SDK.CardDateBegin();
            End = SDK.CareDateEnd();
            iKind = SDK.CardKind();
            Log.e("tag", "读取到数据: ");
            if (Fp != 0) {
                sFp = SDK.CardFp();
                //测试只显示前10个字节
                if (sFp.length() >= 10) {
                    sFp = "指纹数据 " + sFp.substring(0, 10);
                }
            }
            switch (iKind) {
                case 1: {
                    Folk = SDK.CardFolk(); //只有身份证有名族字段
                    Kind = "证件类型 身份证";
                    break;
                }
                case 2: {
                    Count = "签发次数 " + SDK.CardCount();
                    switch (SDK.SubKind()) {
                        case 1: {
                            Kind = "证件类型 香港";
                            break;
                        }
                        case 2: {
                            Kind = "证件类型 澳门";
                            break;
                        }
                        case 3: {
                            Kind = "证件类型 台湾";
                            break;
                        }
                    }
                    break;
                }
                case 3: {
                    EnglishName = "英文名称 " + SDK.CardEnglishName();
                    AreaCode = "国籍代码 " + SDK.CardAreaCode() + "\r\n" + "当次申请受理机构代码" + SDK.CardAgencyCode();
                    Version = "证件版本号 " + SDK.CardVersion();
                    Kind = "证件类型 外国人";
                    break;
                }
                default: {
                    Kind = "未知";
                    break;
                }
            }
        }
        return ret;
    }


    private void unInitEngine() {
//        if (faceEngine != null) {
//            faceEngine.unInit();
//        }
    }

    @Override
    protected void onDestroy() {
        unInitEngine();
        super.onDestroy();
    }

    @Override
    public void init(@Nullable Bundle savedInstanceState) {

        settitle("身份证信息读取");
        img = findViewById(R.id.img);

//        faceEngine = new FaceEngine();
//        int faceEngineCode = faceEngine.init(this, DetectMode.ASF_DETECT_MODE_IMAGE, DetectFaceOrientPriority.ASF_OP_0_ONLY,
//                16, 6, FaceEngine.ASF_FACE_RECOGNITION | FaceEngine.ASF_AGE | FaceEngine.ASF_FACE_DETECT | FaceEngine.ASF_GENDER | FaceEngine.ASF_FACE3DANGLE);


        m_Info = findViewById(R.id.m_Info);
        SDK = new M53M513Serial();
        //查找所有串口
        String list[] = new SerialPortFinder().getAllDevicesPath();


        if (list.length > 0) {
            for (int i = 0; i < list.length; i++) {
                if (list[i].indexOf("ttyS2") > 0) {
                    SerialName = list[i];
                    //自动打开
                    EventOpen();
                    break;
                }

            }
        } else {
            ToastUtils.showShort("没有找到串口");
        }

    }

    @Override
    public int getContentView() {
        return R.layout.activity_i_d_car_read2;
    }
}